package com.wn.ziroombackend.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wn.ziroombackend.entity.Cleaner;
import com.wn.ziroombackend.entity.OrderClr;
import com.wn.ziroombackend.service.OrderClrService;
import com.wn.ziroombackend.service.impl.CleanerServiceImpl;
import com.wn.ziroombackend.utils.FtpUtil;
import com.wn.ziroombackend.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.naming.Name;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Wrapper;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wangzhijia
 * @since 2023-02-27 10:56:29
 */
@RestController
@RequestMapping("/cleaner")
public class CleanerController {

    CleanerServiceImpl cleanerService;

    @Autowired
    OrderClrService orderClrService;

    StringRedisTemplate redisTemplate;

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setCleanerService(CleanerServiceImpl cleanerService) {
        this.cleanerService = cleanerService;
    }

    @GetMapping("/list")
    public R list() {
        List<Cleaner> list = cleanerService.list();
        return R.ok("200").data("list", list);
    }

    @GetMapping("searchOne")
    public R searchOne(Integer id) {

        Cleaner one = cleanerService.getById(id);
        return R.ok("ok").data("cleaner", one);
    }

    @PostMapping("/editOneCleanerInfo")
    public R editOneCleanerInfo(@RequestBody Cleaner cleaner) {
        System.out.println("修改后的信息" + cleaner);

        boolean b = cleanerService.updateById(cleaner);
        return R.ok("ok");
    }

    @PostMapping("/uploadImg")
    public R uploadImg(@RequestParam(value = "myHeader") MultipartFile multipartFile) {

        //获取文件上传的名字
        String filename = multipartFile.getOriginalFilename();

        //修改文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");

        //获取文件后缀
        String subfix = filename.substring(filename.lastIndexOf("."));

        //给文件重命名
        filename = "CLR_" + uuid + subfix;


        System.out.println("照片的名字为:" + filename);

        try (InputStream inputStream = multipartFile.getInputStream()) {
            //创建上传对象
            FtpUtil.uploadFile("139.224.186.148", 21, "781974288", "ekwJdKiTWSFwG2YZ", "/",
                    "/", filename, inputStream);


            return R.ok("ok").data("filename", filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    @GetMapping("/conditionList")
    public R conditionList(@RequestParam(value = "name") String name,
                           @RequestParam(value = "area") String area,
                           @RequestParam(value = "street") String street,
                           @RequestParam(value = "state") String state,
                           @RequestParam(value = "pageNum") int pageNum,
                           @RequestParam(value = "pageSize") int pageSize) {
        System.out.println("name:" + name);
        System.out.println("area:" + area);
        System.out.println("street:" + street);
        System.out.println("state:" + state);

        QueryWrapper<Cleaner> wrapper = new QueryWrapper<>();
        HashMap<String, String> map = new HashMap<>();

        if (!name.equals("")) {
            wrapper.like("clr_name", name);
        }
        if (!area.equals("")) {
            map.put("clr_area", area);
        }
        if (!street.equals("")) {
            map.put("clr_street", street);
        }
        if (!state.equals("")) {
            map.put("clr_state", state);
        }

        wrapper.allEq(map);
        PageHelper.startPage(pageNum, pageSize);
        List<Cleaner> list = cleanerService.list(wrapper);

        System.out.println(list);

        return R.ok("ok").data("list", new PageInfo<>(list));
    }

    @PostMapping("/addOneCleanerInfo")
    public R addOneCleanerInfo(@RequestBody Cleaner cleaner) {
        System.out.println(cleaner);
        cleanerService.save(cleaner);
        return R.ok("ok");
    }

    @GetMapping("/dispatchCleanerList")
    public R dispatchCleanerList(@RequestParam(value = "starttime") String starttime, @RequestParam(value = "duration") String duration,
                                 @RequestParam(value = "areasId") String areasId,
                                 @RequestParam(value = "streetsId") String streetsId) {
        System.out.println(areasId);
        System.out.println(streetsId);
        System.out.println(duration);
        String bookDay = starttime.substring(0, starttime.indexOf(" "));
        System.out.println(bookDay);

        String start = starttime.substring(starttime.indexOf(" ") + 1);
        String startCus = start.substring(0, start.indexOf("-"));

        //创建一个不可用清洁员队列备用返回值队列
        HashSet<String> DisabledTeam = new HashSet<String>();


        //用户的开始时间
        System.out.println(startCus);

        int endCus = Integer.parseInt(startCus) + Integer.parseInt(duration);

        Integer[] startTimeSpan = {8, 10, 12, 14};
        Integer[] timeLength = {2, 4, 6, 8};

        for (int i = 0; i < startTimeSpan.length; i++) {

            //开始时间小于等于用户的服务开始时间
            if (startTimeSpan[i] <= Integer.parseInt(startCus)) {

                for (int j = 0; j < timeLength.length; j++) {

                    //结束时间大于等于用户的结束时间  ||  结束时间大于开始时间小于等于开始时间 = 结束时间只要大于用户的开始时间即可
                    if ((startTimeSpan[i] + timeLength[j]) > Integer.parseInt(startCus)) {

                        //查询redis的键
                        String key = bookDay + ":" + startTimeSpan[i] + ":" + timeLength[j];
                        String s = redisTemplate.opsForValue().get(key);
                        System.out.println("key:" + key + "\n" + "result:" + s);

                        //放入不可用清洁员队列
                        if (s != null) {

                            String[] split = s.split(",");
                            for (String tempS : split
                            ) {
                                System.out.println(tempS);
                                DisabledTeam.add(tempS);
                            }
                        }
                    }

                }
            }


            //开始时间小于用户的服务结束时间
            if (startTimeSpan[i] <= endCus) {

                for (int j = 0; j < timeLength.length; j++) {

                    //结束时间大于等于用户的服务结束时间
                    if ((startTimeSpan[i] + timeLength[j]) >= endCus) {

                        //查询redis的键
                        String key = bookDay + ":" + startTimeSpan[i] + ":" + timeLength[j];
                        String s = redisTemplate.opsForValue().get(key);
                        System.out.println("key:" + key + "\n" + "result:" + s);

                        //放入不可用清洁员队列
                        if (s != null) {

                            String[] split = s.split(",");
                            for (String tempS : split
                            ) {
                                System.out.println(tempS);
                                DisabledTeam.add(tempS);
                            }
                        }
                    }

                }
            }

            //开始时间大于等于用户的开始时间
            if (startTimeSpan[i] >= Integer.parseInt(startCus)) {

                for (int j = 0; j < timeLength.length; j++) {

                    //结束时间小于等于用户的结束时间
                    if ((startTimeSpan[i] + timeLength[j]) <= endCus) {

                        //查询redis的键
                        String key = bookDay + ":" + startTimeSpan[i] + ":" + timeLength[j];
                        String s = redisTemplate.opsForValue().get(key);
                        System.out.println("key:" + key + "\n" + "result:" + s);

                        //放入不可用清洁员队列
                        if (s != null) {

                            String[] split = s.split(",");
                            for (String tempS : split
                            ) {
                                System.out.println(tempS);
                                DisabledTeam.add(tempS);
                            }
                        }
                    }

                }
            }
        }

        //查询所有该地区的清洁员
        QueryWrapper<Cleaner> wrapper = new QueryWrapper<>();
        HashMap<String, String> map = new HashMap<>();
        map.put("clr_area", areasId);
        map.put("clr_street", streetsId);
        map.put("clr_state", "1");
        wrapper.allEq(map);
        List<Cleaner> list = cleanerService.list(wrapper);


        System.out.println("---------------");
        Object[] endTeam = DisabledTeam.toArray();

        System.out.println("--------------------");
        Iterator<Cleaner> iterator = list.iterator();
        System.out.println(endTeam);

        while (iterator.hasNext()) {
            Cleaner next = iterator.next();
            System.out.println(next);
            for (int i = 0; i < endTeam.length; i++) {
                if ((next.getId().toString()).equals((String) endTeam[i])) {
                    System.out.println("a:" + next.getId() + ",b:" + endTeam[i]);
                    iterator.remove();
                }
            }
        }

        System.out.println("-----------");
        for (Cleaner c : list
        ) {
            System.out.println(c);
        }

        return R.ok("ok").data("list", list);
    }

    @GetMapping("/editDispatch")
    public R editDispatch(@RequestParam(value = "orderClrId") String orderClrId,
                          @RequestParam(value = "clrId") String clrId,
                          @RequestParam(value = "orderStarttime") String orderStarttime,
                          @RequestParam(value = "orderDuration") String orderDuration) {
        System.out.println(orderClrId);
        System.out.println(clrId);
        String bookDay = orderStarttime.substring(0, orderStarttime.indexOf(" "));
        System.out.println(bookDay);
        String starttime = orderStarttime.substring(orderStarttime.indexOf(" ") + 1);

        starttime = starttime.substring(0, starttime.indexOf("-"));
        System.out.println(starttime);

        System.out.println(orderDuration);

        //得到key去查询
        String key = bookDay + ":" + Integer.parseInt(starttime) + ":" + Integer.parseInt(orderDuration);
        String s = redisTemplate.opsForValue().get(key);
        System.out.println("key:" + key + "\n" + "result:" + s);

        //如果redis没有则添加
        if (s == null) {
            redisTemplate.opsForValue().set(key, clrId + ",");
        } else {
            //如果redis有的话就先删除后添加
            s = s + clrId + ",";
            redisTemplate.opsForValue().getAndDelete(key);
            redisTemplate.opsForValue().set(key, s);
        }

        //修改数据库

        OrderClr orderClr = new OrderClr();
        orderClr.setId(Integer.parseInt(orderClrId));
        orderClr.setClrId(Integer.parseInt(clrId));
        orderClr.setState("1");
        boolean b = orderClrService.updateById(orderClr);

        return R.ok("ok");
    }

    @GetMapping("/cancelDispatch")
    public R cancelDispatch(@RequestParam(value = "id") String id,
                            @RequestParam(value = "clrId") String clrId,
                            @RequestParam(value = "starttime") String starttime,
                            @RequestParam(value = "duration") String duration) {
        System.out.println(id);
        System.out.println(clrId);
        System.out.println(starttime);
        System.out.println(duration);

        //先移除数据库内的数据
        OrderClr orderClr = new OrderClr();
        orderClr.setId(Integer.parseInt(id));
        orderClr.setClrId(-1);
        orderClr.setState("0");
        boolean b = orderClrService.updateById(orderClr);


        //移除redis里面的数据
        String bookDay = starttime.substring(0, starttime.indexOf(" "));
        System.out.println(bookDay);

        String starttimeTemp = starttime.substring(starttime.indexOf(" ") + 1);

        starttimeTemp = starttimeTemp.substring(0, starttimeTemp.indexOf("-"));
        System.out.println(starttimeTemp);

        //得到key去查询
        String key = bookDay + ":" + Integer.parseInt(starttimeTemp) + ":" + Integer.parseInt(duration);
        String s = redisTemplate.opsForValue().getAndDelete(key);

        if (s != null) {
            if (s.indexOf(",") == s.lastIndexOf(",")) {
                //如果里面只有一个数据
                //不进行操作已经删除
            } else {
                //如果里面不止一个数据
                String replace = s.replace("," + clrId + ",", ",");
                redisTemplate.opsForValue().set(key,replace);
            }
        }
        return R.ok("ok");
    }

    @GetMapping("/testRedis")
    public String testRedis() {
        System.out.println("ok---");
        redisTemplate.opsForValue().set("wsc", "wsc");
        return null;
    }

}

